package com.gotloop.controllers;

import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
@Controller
public class LoginController {

	/**
	 * Logger for LoginController.
	 */
	private static final Logger LOG = LoggerFactory.getLogger(LoginController.class);
	private UserService userService = UserServiceFactory.getUserService();

    private static final Map<String, String> openIdProviders;
    static {
        openIdProviders = new HashMap<String, String>();
        openIdProviders.put("Google", "google.com/accounts/o8/id");
        openIdProviders.put("Yahoo", "yahoo.com");
        openIdProviders.put("MySpace", "myspace.com");
        openIdProviders.put("AOL", "aol.com");
        openIdProviders.put("MyOpenId.com", "myopenid.com");
    }

	@RequestMapping("/login")
	public ModelAndView doLogin(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        User user = userService.getCurrentUser(); // or req.getUserPrincipal()
        Set<String> attributes = new HashSet<String>();

        if (user != null) {
            LOG.info("Hello <i>" + user.getNickname() + "</i>!");
            LOG.info("[<a href=\""
                    + userService.createLogoutURL(req.getRequestURI())
                    + "\">sign out</a>]");
        } else {
        	LOG.info("Hello world! Sign in at: ");
            for (String providerName : openIdProviders.keySet()) {
                String providerUrl = openIdProviders.get(providerName);
                String loginUrl = userService.createLoginURL(req
                        .getRequestURI(), null, providerUrl, attributes);
                LOG.info("[<a href=\"" + loginUrl + "\">" + providerName + "</a>] ");
            }
        }
        return new ModelAndView("loginOK");
    }

}
